const http = require('http');
const WebSocket = require('ws');
const url = require('url');
var MongoClient = require('mongodb').MongoClient;

var config = require('./config.json')
var _server_list = require("./server.json")
var server_list = JSON.parse(JSON.stringify(_server_list))

// token may be seen by the frontend
const server = http.createServer();
const wss1 = new WebSocket.Server({
    noServer: true
});
const wss2 = new WebSocket.Server({
    noServer: true
});

var db = new MongoClient(config["mongo"]);
var connections = db.connect();

wss1.on('connection', function connection(ws) {
    //log the received message and send it back to the client
    ws.on('message', (message) => {
        //log the received message and send it back to the client
        try {
            var msg = JSON.parse(message)
            var server_id = ""
            //if (Date.now() % 10 != 0)
            let temp_date = new Date()
            msg["createdAt"] = temp_date
            msg["locale"] = temp_date.toLocaleTimeString("en-SG", {
                timeZone: 'Asia/Singapore'
            })
            if (msg.token && server_list[msg.token]) {
                server_id = server_list[msg.token]["name"]
                server_list[msg.token]["status"] = msg
                //console.log(server_list[msg.token])
                connections.then(
                    async (db) => {
                        const dbo = db.db("serverstatus");
                        //server
                        var server_collection = dbo.collection(server_id);
                        var _temp = await server_collection.insertOne(msg)
                    }
                )
            }
            //console.log(server_list)

        } catch (e) {
            console.log(message)
            console.log(e)
        }
        //ws.send('something');
    });
});

wss2.on('connection', function connection(ws) {
    // ...
});

server.on('upgrade', function upgrade(request, socket, head) {
    const pathname = url.parse(request.url).pathname;

    if (pathname == config["secret_path"]) {
        wss1.handleUpgrade(request, socket, head, function done(ws) {
            wss1.emit('connection', ws, request);
        });
    } else if (pathname === '/other') {
        wss2.handleUpgrade(request, socket, head, function done(ws) {
            wss2.emit('connection', ws, request);
        });
    } else {
        socket.destroy();
    }
});

server.listen(8080);

module.exports = server_list;